﻿namespace HuwmanCode.ComponentModel.Composition.Hosting

open System
open System.Configuration
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open System.ComponentModel.Composition.Primitives
open System.Reflection

open HuwmanCode
open HuwmanCode.Reflection
open HuwmanCode.ComponentModel.Composition

type ConnectionStringExportProvider () =
    inherit ExportProvider ()
    let getExports (definition:ImportDefinition) =
        if definition.ContractName |> String.IsNullOrWhiteSpace then None
        elif definition.Cardinality <> ImportCardinality.ZeroOrOne && definition.Cardinality <> ImportCardinality.ExactlyOne then None
        else let metadata = dict [(CompositionConstants.ExportTypeIdentityMetadataName, box (typeof<string>.FullName))]
             let connectionStrings:seq<ConnectionStringSettings> = ConfigurationManager.ConnectionStrings |> Seq.cast
             connectionStrings
             |> Seq.map (fun cs -> 
                let exportDefinition = new ExportDefinition (cs.Name, metadata)
                let export = new Export (exportDefinition, fun () -> box (cs.ConnectionString))
                export)
             |> Seq.filter (fun e -> definition.IsConstraintSatisfiedBy (e.Definition))
             |> Some
         
    override this.GetExportsCore (definition, atomicComposition) = 
        match getExports definition with 
        | None -> Seq.empty
        | Some exports -> exports